import { useState, useEffect } from 'react'
import { Modal, message, Form } from 'antd'

import request from '@/utils/request'
import { IForm } from '@/components'
import { FormItemConfig } from '@/components/FormItem'
import { transformTreeData, getAllParentIds } from '@/utils/util'
import { useAppSelector } from '@/utils/hooks'

import { RecordDetail } from '../type'

interface Props {
  detail?: RecordDetail
  editText?: string
  onEdit: (values: RecordDetail) => Promise<any>
}

const EditResourceModal: React.FC<Props> = ({ detail, editText = '编辑', onEdit }) => {
  const [app] = useAppSelector(state => [state.app])
  const [form] = Form.useForm()
  const [open, setOpen] = useState(false)
  const [resources, setResources] = useState<DataNode[]>([])

  useEffect(() => {
    if (open && detail) {
      queryResources()
    }
  }, [open, detail])

  const queryResources = () => {
    const data = {
			tenantId: app.currentEntity.entityId,
			status:1,
			roleType: detail?.roleType }
    request('commonQueryResourcesByEntity', { data }).then(res => {
      if (res?.code === 0) {
        // setResources(transformTreeData(res.data, 'label', 'value'))
        setResources((res.data))
      }
    })
  }

  const handleOk = async () => {
    try {
      const { resourceIds, ...rest } = await form.validateFields()
      const pIds = getAllParentIds(resources, resourceIds)
      onEdit({ ...rest, resourceIds: [...resourceIds, ...pIds] }).then(res => {
        if (res?.code === 0) {
          handleCancel()
        }
      })
    } catch (error) {
      message.warn('信息填写有误！')
    }
  }
  const handleCancel = () => {
    setOpen(false)
  }

  const formItemsConfig: FormItemConfig[] = [
    resources.length && detail?.resourceIds.length
      ? {
          type: 'tree',
          formItemProps: {
            label: '资源点权限',
            name: 'resourceIds',
            valuePropName: 'checkedKeys',
            trigger: 'onCheck',
            rules: [{ required: true }],
            // initialValue:  detail.resourceIds,
						initialValue: (() => {
							// 收集所有叶子节点ID的集合
							const leafNodeIds = new Set();

							// 递归遍历资源树，收集叶子节点ID
							const collectLeafNodes = (nodes: any[]) => {
								nodes.forEach(node => {
									// 如果没有子节点，说明是叶子节点
									if (!node.children || node.children.length === 0) {
										leafNodeIds.add(node.id.toString());
									} else {
										// 有子节点则递归处理
										collectLeafNodes(node.children);
									}
								});
							};
							// 开始收集所有叶子节点
							collectLeafNodes(resources);
							// 筛选出resourceIds中属于叶子节点的ID
							return detail.resourceIds.filter(id => leafNodeIds.has(id));
						})(),
					},
          childProps: {
            defaultExpandedKeys: detail.resourceIds,
            // onCheck(checked, info) {
            //   // 是否需要携带半选的父亲节点
						// 	return {
						// 		checked: checkedKeys, // 全选节点
						// 		halfChecked: info.halfCheckedKeys, // 半选节点
						// 	};
            // },
            treeData: resources as any,
          },
        }
      : null,
  ]

  return (
    <>
      <div className="link" onClick={() => setOpen(true)}>
        {editText}
      </div>
      {open && (
        <Modal
          title="修改资源权限"
          destroyOnClose
          maskClosable={false}
          open={open}
          onOk={handleOk}
          onCancel={handleCancel}
        >
          <IForm
            labelCol={{ span: 5 }}
            layout="vertical"
            form={form}
            formItemsConfig={formItemsConfig}
          ></IForm>
        </Modal>
      )}
    </>
  )
}

export default EditResourceModal
